package web.demo.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {
	//设置连接池
	private static DataSource dataSource;
	static{
		//在类加载的时候，建立连接池
		dataSource=new ComboPooledDataSource();
	}
	
	public static QueryRunner getQueryRunner(){
		try{
			//直接给QueryRunner传入dataSource后，再后续的使用中就不需要传入连接了。
			return new QueryRunner(dataSource);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void closeAll(Connection conn){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
